<template>
  <div id="map" class="map_class"></div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import * as echarts from "echarts";
import getMyMap from "@/api/getMyMap";
import { selectByAdress } from "@/api/population";
import { useRouter } from 'vue-router';

const router = useRouter();

// 存储各区域人口数据
const areaData = ref({});

// 初始化时加载数据
onMounted(async () => {
  await loadPopulationData();
  initMyChart();
});

// 加载人口数据
async function loadPopulationData() {
  const areas = [
    "海港区",
    "山海关区",
    "北戴河区",
    "青龙满族自治县",
    "昌黎县",
    "卢龙县",
    "抚宁区",
  ];

  // 并行请求所有区域数据
  const requests = areas.map((area) => getAreaData(area));
  const results = await Promise.all(requests);

  // 更新areaData
  results.forEach(({ area, data }) => {
    areaData.value[area] = data;
  });
}

// 获取单个区域数据
async function getAreaData(area) {
  try {
    const response = await selectByAdress({ area: area });
    // 提取result中的前三个数据
    const result = response.result || {};
    return {
      area,
      data: {
        resident: result[1] || 0, // 常住人口
        floating: result[2] || 0, // 流动人口
        key: result[3] || 0, // 重点人口
      },
    };
  } catch (error) {
    console.error(`获取${area}数据失败:`, error);
    return {
      area,
      data: {
        resident: 0,
        floating: 0,
        key: 0,
      },
    };
  }
}

const initMyChart = () => {
  const chartDom = document.getElementById("map");
  const myChart = echarts.init(chartDom);
  myChart.showLoading();

  // 获取地图数据并初始化
  getMyMap
    .then((res) => {
      myChart.hideLoading();

      // 注册地图
      echarts.registerMap("QinHuangDao", res.data);

      // 准备地图数据系列
      const mapSeriesData = Object.keys(areaData.value).map((areaName) => {
        return {
          name: areaName,
          value: areaData.value[areaName].resident,
          resident: areaData.value[areaName].resident,
          floating: areaData.value[areaName].floating,
          key: areaData.value[areaName].key,
        };
      });

      const option = {
        title: {
          text: "秦皇岛市人口分布图",
          // subtext: "单位：万人",
          left: "center",
          textStyle: {
            color: "#333",
            fontSize: 18,
          },
        },
        tooltip: {
          trigger: "item",
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          borderColor: "#80cbc4",
          borderWidth: 1,
          padding: 12,
          textStyle: {
            color: "#333",
            fontSize: 14,
          },
          formatter: function (params) {
            if (params.data) {
              const data = params.data;
              return `
              <div style="font-size: 16px; font-weight: bold; color: #0066cc; margin-bottom: 8px;">
                ${params.name}
              </div>
              <div style="margin: 4px 0;">
                <span style="display: inline-block; width: 80px;">常住人口：</span>
                <span style="font-weight: bold; color: #e74c3c;">${data.resident} 人</span>
              </div>
              <div style="margin: 4px 0;">
                <span style="display: inline-block; width: 80px;">流动人口：</span>
                <span style="font-weight: bold; color: #3498db;">${data.floating} 人</span>
              </div>
              <div style="margin: 4px 0;">
                <span style="display: inline-block; width: 80px;">重点人口：</span>
                <span style="font-weight: bold; color: #9b59b6;">${data.key} 人</span>
              </div>
            `;
            }
            return params.name;
          },
        },
        visualMap: {
          min: 20,
          max: 120,
          text: ["高", "低"],
          realtime: false,
          calculable: true,
          inRange: {
            color: ["#e0f7fa", "#80deea", "#4dd0e1", "#26c6da", "#00bcd4"],
          },
          textStyle: {
            color: "#333",
          },
        },
        geo: {
          map: "QinHuangDao",
          roam: true,
          label: {
            show: true,
            color: "#333",
            fontSize: 12,
            formatter: function (params) {
              return params.name;
            },
          },
          emphasis: {
            label: {
              show: true,
              color: "#c2185b",
              fontWeight: "bold",
            },
            itemStyle: {
              areaColor: "#b2ebf2",
            },
          },
          itemStyle: {
            normal: {
              areaColor: "#e0f7fa",
              borderColor: "#80cbc4",
              borderWidth: 1,
            },
          },
        },
        series: [
          {
            name: "人口数据",
            type: "map",
            map: "QinHuangDao",
            geoIndex: 0,
            data: mapSeriesData,
            emphasis: {
              label: {
                show: true,
                formatter: function (params) {
                  return `${params.name}\n常住: ${params.data.resident}万`;
                },
              },
            },
          },
        ],
      };

      myChart.setOption(option);

    // 修改点击事件，添加路由跳转
    myChart.on("click", function (params) {
      router.push({
        name: 'showData',
        query: { area: params.name }
      });
    });

      // 窗口大小变化时调整图表
      window.addEventListener("resize", () => {
        myChart.resize();
      });

      // 添加点击事件
      myChart.on("click", function (params) {
        console.log(
          "区域点击:",
          params.name,
          "人口数据:",
          areaData.value[params.name]
        );
      });
    })
    .catch((error) => {
      console.error("获取地图数据失败", error);
      myChart.hideLoading();
      myChart.setOption({
        title: {
          text: "地图加载失败",
          subtext: "请检查网络连接或数据源",
          left: "center",
          top: "center",
          textStyle: {
            color: "#ff4d4f",
            fontSize: 18,
          },
        },
      });
    });
};
</script>

<style scoped>
.map_class {
  width: 100%;
  height: 100%;
  min-height: 600px;
  background: linear-gradient(to bottom, #f5f7fa, #e4edf5);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e6ed;
}

/* 添加响应式设计 */
@media (max-width: 768px) {
  .map_class {
    min-height: 400px;
    border-radius: 8px;
  }
}
</style>